package com.thenie.chat.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.thenie.chat.service.IUserService;
import com.thenie.chat.vo.RegisterVo;
import com.thenie.chat.vo.RespBean;
import com.thenie.chat.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @Description 注册功能处理器
 * @Author thenie
 * @Data 2022/5/19 14:23
 */
@RestController
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private IUserService userService;
    @Autowired
    private Producer captchaProducer;

    /**
     * 谷歌验证码 生成
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }


    /**
     * 判断是否可以注册
     * @param registerVo
     * @return
     */
    @GetMapping("/canRegister")
    public RespBean checkEmailIsExist(@Valid RegisterVo registerVo){
        String email = registerVo.getEmail();
        String username = registerVo.getUsername();
        if (userService.checkUsernameIsExist(username)){
            return RespBean.error(RespBeanEnum.USERNAME_EXIST);
        }else if (userService.checkEmailIsExist(email)){
            return RespBean.error(RespBeanEnum.EMAIL_EXIST);
        }
        return RespBean.success("可以注册");
    }

    /**
     * 进行注册
     * @param registerVo
     * @param code
     * @param req
     * @param resp
     * @return
     */
    @PostMapping("/doRegister")
    public RespBean register(@Valid RegisterVo registerVo,String code , HttpServletRequest req, HttpServletResponse resp){
        //谷歌验证码获取
        String kaptcha = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //谷歌验证码销毁
        req.removeAttribute(KAPTCHA_SESSION_KEY);

        if (code == null || !code.equals(kaptcha)){
            return RespBean.error(RespBeanEnum.CODE_ERROR);
        }

        //再判断，防止用户直接post提交
        String email = registerVo.getEmail();
        String username = registerVo.getUsername();
        if (userService.checkUsernameIsExist(username)){
            return RespBean.error(RespBeanEnum.USERNAME_EXIST);
        }else if (userService.checkEmailIsExist(email)){
            return RespBean.error(RespBeanEnum.EMAIL_EXIST);
        }
        //用户注册
        return userService.doRegister(registerVo,req,resp);
    }
}
